<template>
  <div>
    <div class="sys-breadcrumb">
      下钻源管理
      <el-button-group class="sys-breadcrumb-handle">
        <el-button type="text" @click="add" icon="el-icon-circle-plus">新增下钻数据源</el-button>
      </el-button-group>
    </div>
    <el-card>
      <el-table :data="list" style="width: 100%" border stripe>
        <el-table-column prop="name" width="120px" label="名称"></el-table-column>
        <el-table-column prop="bindDataType" width="120px" label="绑定数据类型">
          <template slot-scope="scope">
            <span v-if="scope.row.bindDataType === 1">SQL建模</span>
            <span v-else>API拉取</span>
          </template>
        </el-table-column>
        <el-table-column prop="dataMapping" label="映射关系"></el-table-column>
        <el-table-column prop="action" width="200px" label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="edit(scope.row)">修改</el-button>
            <el-button type="text" @click="remove(scope.row)">删除</el-button>
            <el-button type="text" @click="jsonmap(scope.row)">字段映射</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align:center; margin-top: 30px;">
        <el-pagination
          background
          :page-size="search.size"
          @current-change="handleCurrentChange"
          :current-page.sync="search.page"
          layout="prev, pager, next"
          :total="search.total">
        </el-pagination>
      </div>
    </el-card>
    <el-dialog :title="form.id == 0 ? '新增下钻': '修改下钻'" :visible.sync="form.show">
      <el-form ref="form" status-icon :model="form" :rules="rules">
        <el-form-item label="名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="数据源" :label-width="formLabelWidth" prop="bindDataType">
          <el-radio-group v-model="form.bindDataType" @change="resetDatabases">
            <el-radio-button :label="1">SQL建模</el-radio-button>
            <el-radio-button :label="2">API拉取</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="源名称" :label-width="formLabelWidth" prop="bindDataId">
          <el-select
            v-model="form.bindDataId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            @change="setSource"
            :remote-method="handleRemoteDataSource">
            <el-option
              v-for="item in datasource"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="请选择显示列" :label-width="formLabelWidth" prop="showFields">
          <el-select
            multiple
            v-model="form.showFields"
            @change="test"
            style="width: 80%"
            placeholder="请选择">
            <el-option
              v-for="item in fieldMapping"
              :key="item.field_name"
              :label="item.show_name"
              :value="item.field_name">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      {{testResult}}
      <div slot="footer" class="dialog-footer">
        <el-button @click="testapi">调试API</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </div>
    </el-dialog>
    <el-dialog title="字段映射" :visible.sync="jsonData.show">
      <div id="jsoneditor"></div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="savejson">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Services from "@/services";
export default {
  data() {
    return {
      formLabelWidth: "120px",
      form: {
        id: 0,
        show: false,
        name: "",
        chartType: 1,
        bindDataType: null,
        bindDataId: null,
        dataMapping: "[{'field_name':'name','show_name':'名字','field_type':'String'},{'field_name':'entry_date','show_name':'发布时间','field_type':'Date'}]",
        showFields: [],
        chartConfig: ''
      },
      datasource: [],
      editor: null,
      search:{
        page: 1,
        size: 20,
        total: 0 ,
      },
      jsonData: {
        show: false
      },
      list: [],
      databases: [],
      fieldMapping: [],
      rules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        showFields: [{ required: true, message: '请选择显示列', trigger: 'blur' }],
        bindDataId: [{ required: true, message: '请选择绑定源名称', trigger: 'blur' }],
      },
      testResult: ""
    };
  },
  created() {
    this.http();
  },
  methods: {
    http() {
      Services.DRILL_LIST(this.search).then(res => {
        this.list = res.rows
      });
    },
    handleCurrentChange(e){
      this.search.page = e
      this.http()
    },
    add() {
      this.form = {
        id: 0,
        show: true,
        name: "",
        chartType: 1,
        bindDataType: 1,
        bindDataId: null,
        dataMapping: "[{'field_name':'name','show_name':'名字','field_type':'String'},{'field_name':'entry_date','show_name':'发布时间','field_type':'Date'}]",
        showFields: [],
        chartConfig: ''
      }
    },
    setDatabase(e){
      this.databases.forEach(database => {
        if(database.id === e){
          this.form.dsName = database.name
        }
      })
    },
    testapi() {
      if(this.form.bindDataType === 1){
        Services.SQL_TEST(this.form.dsSqlDO).then(res => {
          this.testResult = res.data
          this.$message.success('测试通过')
        });
      } else {
        Services.API_TEST({
          id: this.form.id
        }).then(res => {
          this.testResult = res
          this.$message.success('测试通过')
        });
      }
      


      // Services.DATABASE_TEST(this.form).then(res => {
      //   this.databases.forEach(database => {
      //     console.log(databases)
      //   })
      // });
    },
    submit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          // this.form.fieldMapping = JSON.stringify(this.form.fieldMapping)
          this.form.chartConfig = JSON.stringify({
            showFields: this.form.showFields
          })
          if(this.form.id == 0){
            Services.DRILL_ADD(this.form).then(res => {
              if(res.code == 0){
                this.$message({
                  message: res.msg,
                  type: 'success'
                });
                this.form.show = false
                this.http()
              } else {
                this.$message({
                  message: res.msg,
                  type: 'error'
                });
              }
            })
          } else {
            Services.DRILL_EDIT(this.form).then(res => {
              if(res.code == 0){
                this.$message({
                  message: res.msg,
                  type: 'success'
                });
                this.form.show = false
                this.http()
              } else {
                this.$message({
                  message: res.msg,
                  type: 'error'
                });
              }
            })
          }
          
        } 
      });
    },
    edit(api) {
      this.datasource = [{
        id: api.dsSqlDO.id,
        name: api.dsSqlDO.dsName
      }]
      let fieldMappingStr = api.dsSqlDO.fieldMapping.replace(/'/g, '"')
      this.fieldMapping = JSON.parse(fieldMappingStr)
      this.testResult = ''
      this.form = {
        ...api,
        show: true
      }
    },
    remove(api) {
      this.$confirm("此操作将永久删除该API, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        Services.DRILL_REMOVE({
          id: api.id
        }).then(res => {
          this.http()
        });
      });
    },
    // 获取数据源
    handleRemoteDataSource(e, component){
      if(this.form.bindDataType == 1){
        Services.SQL_LIST({
          name: e,
          page: 1,
          size: 10
        }).then(res => {
          this.datasource = res.rows
        })
      } else {
        Services.API_LIST({
          name: e,
          page: 1,
          size: 10
        }).then(res => {
          this.datasource = res.rows
        })
      }
    },
    setSource(e){
      this.datasource.forEach(database => {
        if(database.id == e){
          let fieldMappingStr = database.fieldMapping.replace(/'/g, '"')
          this.fieldMapping = JSON.parse(fieldMappingStr)
          this.form.showFields = []
        }
      })
    },
    resetDatabases(){
      this.databases = []
    },

    // 字段映射 显示
    jsonmap(dirll) {
      this.form = {
        ...dirll,
      }
      this.jsonData.show = true
      this.$nextTick(function(){
        if(this.editor) {
          this.editor.destroy()
        }
        let container = document.getElementById('jsoneditor')
        let options = {
          mode: 'text',
          indentation: 2,
          search: true
        }
        this.editor = new this.$jsoneditor(container, options)
        let dataMappingStr = dirll.dataMapping.replace(/'/g, '"')
        try {
          const jsonobj = JSON.parse(dataMappingStr)
          this.editor.set(jsonobj)
        } catch (error) {
          this.editor.set(dirll.dataMapping)
        }
      })
    },
    // 字段映射 保存
    savejson() {
      var json = this.editor.get()
      this.form.dataMapping = JSON.stringify(json)
      Services.DRILL_EDIT(this.form).then(res => {
        if(res.code == 0){
          this.$message({
            message: res.msg,
            type: 'success'
          });
          this.form.show = false
          this.jsonData.show = false
          this.http()
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          });
        }
      })
    },
    test(e){
      this.form.showFields = e
      // console.log(e)
    }
  }
};
</script>
<style lang="less">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
#jsoneditor{
  height: 400px;
}
.jsoneditor-menu{
  display: none;
}
div.jsoneditor-outer.has-main-menu-bar{
  margin-top: 0px;
  padding-top: 0px;
}
   
</style>
